package com.seaboxdata.scheduler;

import com.seaboxdata.entity.DataMonitorConfig;
import com.seaboxdata.entity.DataMonitorResult;
import com.seaboxdata.service.DataMonitorConfigService;
import com.seaboxdata.service.DataMonitorResultService;
import com.seaboxdata.util.MonitorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Configuration
@Slf4j
public class DataMonitorJob {

    @Autowired
    private DataMonitorConfigService dataMonitorConfigService;
    @Autowired
    private DataMonitorResultService dataMonitorResultService;

    @Value("${sms.interval}")
    private String invalidIntervalSecond;

    @Value("${isSmsMonitor}")
    private String isSmsMonitor;

    private String startScript = "restart.sh";

    @Value("${table_names}")
    private String TABLE_NAMES;

    @Value("${script_paths}")
    private String SCRIPT_PATHS;

    @Scheduled(cron = "${interface.DataMonitor}")
    public void doCollect() {
        //如果是sms监控,则调用,如果是数据监控部署,在空调用
        if (!"true".equals(isSmsMonitor)) {
            log.info("==============数据监控 DataMonitorJob start===============");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            List<DataMonitorConfig> list = dataMonitorConfigService.list();
            Date date = null;
            List<DataMonitorResult> resultList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(list)) {
                for (DataMonitorConfig config : list) {
                    DataMonitorResult result = dataMonitorResultService.getResult(config);
                    if (result == null) {
                        result = new DataMonitorResult();
                    }
                    result.setMonitorDate(new Date());
                    date = new Date();
                    String dateStr = sdf.format(date);
                    result.setMonitorDay(dateStr);
                    result.setSchemeName(config.getSchemeName());
                    result.setTableName(config.getTableName());
                    MonitorUtil.setResult(result, config,invalidIntervalSecond);
                    int totalCount = dataMonitorResultService.getTotalCount(config);
                    result.setTotalCount(totalCount);
                    resultList.add(result);
                }
            }
            if (!CollectionUtils.isEmpty(resultList)) {
                dataMonitorResultService.saveBatch(resultList);
            }
            log.info("==============数据监控 DataMonitorJob end===============");
        }

    }

    /**
     * 定时重启指定脚本  暂无用
     */
    @Scheduled(cron = "${interface.DataMonitorReStart}")
    public void reStartJob() {
        //如果是sms监控,则调用,如果是数据监控部署,在空调用
        if (!"true".equals(isSmsMonitor)) {
            log.info("==============数据监控重启方法 reStartJob start===============");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            List<DataMonitorConfig> list = dataMonitorConfigService.list();
            if (!CollectionUtils.isEmpty(list)) {
                for (DataMonitorConfig config : list) {
                    DataMonitorResult result = dataMonitorResultService.getResult(config);
                    if (result == null) {
                        result = new DataMonitorResult();
                    }
                    result.setMonitorDate(new Date());
                    date = new Date();
                    String dateStr = sdf.format(date);
                    result.setMonitorDay(dateStr);
                    result.setSchemeName(config.getSchemeName());
                    result.setTableName(config.getTableName());
                    MonitorUtil.setResult(result, config,invalidIntervalSecond);
                    if ("异常".equals(result.getResult())) {
                        //添加重启机制
                        log.info("=======异常表名：{}",result.getTableName());
                        String[] tableNames = StringUtils.split(TABLE_NAMES,",");
                        String[] scriptPaths = StringUtils.split(SCRIPT_PATHS,",");
                        for (int i = 0; i < tableNames.length; i++) {
                            String tableName = tableNames[i];
                            if (tableName.equals(result.getTableName())){
                                callScript(startScript, "", scriptPaths[i]);
                            }
                        }
                    }
                }
            }
            log.info("==============数据监控重启方法 reStartJob end===============");
        }

    }

//    public void setResult(DataMonitorResult result, DataMonitorConfig config) {
//        if (result.getTotalCount() == null || result.getTotalCount() == 0) {
//            result.setResult("异常");
//        }
//
//        switch (config.getPeriodUnit()) {
//            case "S": {
//                if (result.getLastCjsj() == null) {
//                    result.setResult("异常");
//                } else if (DateUtils.addMinutes(result.getLastCjsj(), Integer.valueOf(invalidIntervalSecond))
//                        .compareTo(result.getMonitorDate()) == -1) {
//                    result.setResult("异常");
//                } else {
//                    result.setResult("正常");
//                }
//                break;
//            }
//            default: {
//                result.setResult("正常");
//            }
//        }
//    }

    private void callScript(String script, String args, String... workspace) {
        Process process = null;
        try {
            String cmd = "sh " + script + " " + args;
            File dir = null;
            if (workspace[0] != null) {
                dir = new File(workspace[0]);
                System.out.println(workspace[0]);
            }
//            String[] evnp = {"val=2", "call=Bash Shell"};
            log.info(dir + " start====");
            process = Runtime.getRuntime().exec(cmd, null, dir);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                log.info("line===={}", line);
            }
            input.close();
            log.info(dir + " end====");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
